﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using Microsoft.Office.Tools.Excel.Extensions;

namespace Lexalytics4Excel
{
    public partial class LexalyticsAddIn
    {
        #region Member data
        /// <summary>
        /// Collection of current open projects across open workbooks, identified by workbook name
        /// </summary>
        public SortedList<string, DataProject> OpenProjects;
        /// <summary>
        /// Data project associated with the currently active workbook
        /// </summary>
        public DataProject CurrentProject;
        #endregion

        #region Event handlers
        /// <summary>
        /// Event handler for Addin Startup. Initialize the data project, set up 
        /// the initial ribbon state, and wire up the event handlers.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            this.Application.WorkbookActivate += new Microsoft.Office.Interop.Excel.AppEvents_WorkbookActivateEventHandler(Application_WorkbookActivate);
            this.Application.WorkbookOpen += new Microsoft.Office.Interop.Excel.AppEvents_WorkbookOpenEventHandler(Application_WorkbookOpen);
            this.Application.SheetFollowHyperlink += new Microsoft.Office.Interop.Excel.AppEvents_SheetFollowHyperlinkEventHandler(Application_SheetFollowHyperlink);
            this.Application.WorkbookBeforeClose += new Microsoft.Office.Interop.Excel.AppEvents_WorkbookBeforeCloseEventHandler(Application_WorkbookBeforeClose);

            OpenProjects = new SortedList<string, DataProject>();
            foreach (Excel.Workbook wb in Application.Workbooks)
            {
                CurrentProject = new DataProject();
                OpenProjects.Add(wb.Name, CurrentProject);
            }
            Globals.Ribbons.SalienceRibbon.SetRibbonState();
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }
        #endregion

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion

        #region Workbook and sheet event handlers

        /// <summary>
        /// Handler for workbook activation
        /// </summary>
        /// <param name="Wb">The workbook which has been activated</param>
        void Application_WorkbookActivate(Microsoft.Office.Interop.Excel.Workbook Wb)
        {
            // Set the current project
            if (OpenProjects.ContainsKey(Wb.Name))
                CurrentProject = OpenProjects[Wb.Name];
            else
            {
                CurrentProject = new DataProject();
                OpenProjects.Add(Wb.Name, CurrentProject);
            }
            Globals.Ribbons.SalienceRibbon.SetRibbonState();
        }

        /// <summary>
        /// Delegate method to handle opening a new workbook
        /// </summary>
        /// <param name="Wb">The workbook being opened</param>
        void Application_WorkbookOpen(Microsoft.Office.Interop.Excel.Workbook Wb)
        {
            CurrentProject = new DataProject();
            OpenProjects.Add(Wb.Name, CurrentProject);
            Globals.Ribbons.SalienceRibbon.SetRibbonState();
        }

        /// <summary>
        /// Event handler for workbook close. If the workbook being closed is the 
        /// only one available, disable the Ribbon.
        /// </summary>
        /// <param name="Wb"></param>
        /// <param name="Cancel"></param>
        void Application_WorkbookBeforeClose(Microsoft.Office.Interop.Excel.Workbook Wb, ref bool Cancel)
        {
            int nWorkbooks = 0;
            foreach (Excel.Workbook wbook in Application.Workbooks)
            {
                if (wbook.Name != Wb.Name)
                    nWorkbooks++;
            }
            if (OpenProjects.ContainsKey(Wb.Name))
                OpenProjects.Remove(Wb.Name);

            if (nWorkbooks == 0)
                Globals.Ribbons.SalienceRibbon.DisableRibbon();

        }

        /// <summary>
        /// Delegate method to handle hyperlink follow in order to toggle named range if target of hyperlink
        /// </summary>
        /// <param name="sheet">The worksheet which triggered the event</param>
        /// <param name="target">The hyperlink target for the event</param>
        void Application_SheetFollowHyperlink(object sheet, Excel.Hyperlink target)
        {
#if DEBUG
            System.Diagnostics.Debug.WriteLine(target.SubAddress);
#endif
            if (target.SubAddress.Contains("LXAEntityDetails_"))
            {
                string rangeName = target.SubAddress.Substring(target.SubAddress.IndexOf("!") + 1);
                Excel.Name rgName = ((Excel.Worksheet)sheet).Names.Item(rangeName, Type.Missing, Type.Missing);
                Excel.Range r = rgName.RefersToRange;
                if (r.EntireRow.Hidden.Equals(true))
                    r.EntireRow.Hidden = false;
                else
                    r.EntireRow.Hidden = true;
            }
        }

        #endregion
    }
}
